package cn.wiscofile.conn;

import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import java.sql.DriverManager;
import javax.naming.InitialContext;


public class DBUtil {
    public DBUtil() {
        super();
    }

    public Connection getConnection() throws SQLException {
        String dsName = ConfigUtil.getInstance().getParameter(
                "connection.datasource");
        try {
            if (dsName != null && !dsName.trim().equals("")) {
                String user = ConfigUtil.getInstance().getParameter(
                        "connection.username");
                String pwd = ConfigUtil.getInstance().getParameter(
                        "connection.password");
                InitialContext ctx = new InitialContext();
                if (user != null && !user.trim().equals(""))
                    return ((DataSource) ctx.lookup(dsName)).getConnection(user,
                            pwd);
                else
                    return ((DataSource) ctx.lookup(dsName)).getConnection();
            } else {
                Class.forName(ConfigUtil.getInstance().getParameter(
                        "connection.driver_class"));
                return DriverManager.getConnection(
                        ConfigUtil.getInstance().getParameter("connection.url"),
                        ConfigUtil.getInstance().getParameter(
                                "connection.username"),
                        ConfigUtil.getInstance().getParameter(
                                "connection.password"));
            }
        } catch (Exception e) {
            throw new SQLException(
                    "DBUtil.getConnection: Exception connection db pool \n" +
                    e.getMessage());
        }
    }

    public Connection getThinConnection() throws SQLException {
        try {
            Class.forName(ConfigUtil.getInstance().getParameter(
                    "connection.driver_class"));
            return DriverManager.getConnection(
                    ConfigUtil.getInstance().getParameter("connection.url"),
                    ConfigUtil.getInstance().getParameter(
                            "connection.username"),
                    ConfigUtil.getInstance().getParameter(
                            "connection.password"));
        } catch (Exception e) {
            throw new SQLException(
                    "DBUtil.getConnection: Exception connection db pool \n" +
                    e.getMessage());
        }
    }

    public String inDbEncode(String value) {
        return value;
    }

    public String outDbEncode(String value) {
        return value;
    }

}
